package com.eqdd.yiqidian.ui.mine.space.fragment

import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.LeaveMessageBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonConverter
import com.eqdd.yiqidian.kotlin.toArrayList
import com.eqdd.yiqidian.ui.base.EditTextActivity
import com.eqdd.yiqidian.ui.mine.UserCardActivity
import com.eqdd.yiqidian.utils.TimeUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.fragment_company_space.*
import kotlinx.android.synthetic.main.fragment_company_space.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.support.v4.startActivityForResult
import org.jetbrains.anko.support.v4.toast
import java.util.*

/**
 * Created by jhj on 18-7-4.
 */
class MessageFragment : Fragment() {

    var mvcHelper: MVCCoolHelper<List<LeaveMessageBean>>? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_company_space, container, false)
        initView(view)
        return view
    }

    private var userCompanyId: Int? = null
    private var companyId: Int? = null
    private var userGuid: String? = null

    private fun initView(view: View) {
        view.layout_add.visibility = View.VISIBLE
        view.layout_add.onClick {
            startActivityForResult<EditTextActivity>(1000, "title" to "留言", "tip" to "留言")
        }
        view.recyclerView.layoutManager = LinearLayoutManager(activity)
        view.recyclerView.addItemDecoration(DividerLineItemDecoration(activity))
        var pageNum = 0
        companyId = arguments?.getInt(Config.COMPANY_ID, -1)
        userCompanyId = arguments?.getInt("userCompanyId", -1)
        userGuid = arguments?.getString(Config.GUID)
        if (companyId == null || companyId == -1) {
            return
        }
        mvcHelper = MVCCoolHelper<List<LeaveMessageBean>>(view.coolRefreshView)
        val list = arrayListOf<LeaveMessageBean>()
        val slimAdapterEx = SlimAdapterEx.create().register<LeaveMessageBean>(R.layout.list_item_161, SlimInjector<LeaveMessageBean> { data, injector ->
            injector?.text(R.id.tv_name, data?.staffName)
                    ?.text(R.id.tv_depart, String.format(Locale.CHINA, "%s - %s", data?.departName, data?.postName))
                    ?.text(R.id.tv_time, TimeUtil.formatWebTime(data?.createTime))
                    ?.imageCircle(R.id.iv_photo, data?.iphoto)
                    ?.text(R.id.tv_message, data?.message)
                    ?.with<RecyclerView>(R.id.recyclerView) {
                        it.layoutManager = LinearLayoutManager(activity)
                        SlimAdapterEx.create().register<LeaveMessageBean>(R.layout.list_item_162, SlimInjector<LeaveMessageBean> { t1, t2 ->
                            t2?.text(R.id.tv_reply, t1?.message)
                        }).attachTo(it).updateData(data?.childList?.toArrayList() as List<LeaveMessageBean>)
                    }
                    ?.clicked(R.id.iv_photo) {
                        data?.creater?.let {
                            startActivity<UserCardActivity>(Config.GUID to it)
                        }
                    }
        }).attachTo(view.recyclerView).updateData(list as List<LeaveMessageBean>?) as SlimAdapterEx<LeaveMessageBean>?
        /*ItemClickSupport.addTo(view.recyclerView).setOnItemClickListener { recyclerView, position, v ->
            activity?.startActivity<LeaveMessageInfoActivity>(Config.ID to slimAdapterEx?.getDataItem(position)?.id)
        }*/
        val dataSource = ModelRx2DataSource<LeaveMessageBean>(ModelRx2DataSource.OnLoadSource<LeaveMessageBean> { page, register ->
            if (page == 1) {
                pageNum = 0
            }
            OkGo.post<HttpResult<List<LeaveMessageBean>>>(HttpConfig.BASE_URL + HttpConfig.LEAVE_MESSAGE_LIST)
                    .params("companyId", companyId ?: 0)
                    .params("page", pageNum)
                    .converter(object : JsonConverter<HttpResult<List<LeaveMessageBean>>>() {
                        override fun test() {
                            super.test()
                        }
                    }).adapt(FlowableBody<HttpResult<List<LeaveMessageBean>>>())
                    .flatMap({ result ->
                        if (page == 1) {
                            mvcHelper?.isAutoLoadMore = true
                        }
                        pageNum = result.page
                        Flowable.just<MutableList<LeaveMessageBean>>(if (result.items == null) ArrayList() else result.items as MutableList<LeaveMessageBean>?)
                    })
        }, 10)


        mvcHelper?.setDataSource(dataSource)
        mvcHelper?.adapter = slimAdapterEx
        mvcHelper?.refresh()
    }

    private fun leaveMessaeg(msg: String) {
        OkGo.post<HttpResult<LeaveMessageBean>>(HttpConfig.BASE_URL + HttpConfig.LEAVE_MESSAGE_ADD)
                .params("userGuid", userGuid)
                .params("userCompanyId", userCompanyId ?: 0)
                .params("message", msg)
                .params("companyId", companyId ?: 0)
                .params("parentId",  0)
                .params("parentUserGuid", 0)
                .params("firstCommentId", 0)
                .execute(object : DialogCallBack<HttpResult<LeaveMessageBean>>(activity) {
                    override fun onSuccess(response: Response<HttpResult<LeaveMessageBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            mvcHelper?.refresh()
                        } else {
                            toast(result?.msg ?: "")
                        }
                    }

                })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Config.INTENT_CONTENT) {
            when (requestCode) {
                1000 -> {
                    val str = data?.getStringExtra(Config.CONTENT)
                    leaveMessaeg(str ?: "")
                }
            }
        }

    }


}